
var AccountsView = View.extend(AccountsView = {
   
    init: function() {
        this.accounts.init();
        this.roles.init();
    },
    
    accounts: {
        init: function() {
            this.bindUI();
        },
        
        bindUI: function() {
            var self = this;
            
            $("#add_account_btn").click(function() {
                self.addAccountTmpl();
            });
            
            $("#accounts_list").on('click', ".account_remove", function() {
                var panel = $(this).parents('.account_panel');
                
                if( panel.data('id') == '' ) {
                    panel.hide('fast').remove();
                }
                
                else {
                    self.remove( panel.data('id'), function() {
                        panel.hide('fast').remove();
                    });
                }
            });
            
            $("#accounts_list").on('changed', '.select', function() {
                var value = $(this).select('selectedItem').value;
                
                $(this).parents('.account_panel').find('.organisation_role_id').val(value);
                self.enableButtons(true);
            });
            
            $("#accounts_list_form").submit(function(e) {
                e.preventDefault();
                self.save();
            });
        },
        
        enableButtons: function(enable) {
            if( enable ) {
                $(".buttons button").removeAttr('disabled');
            }
            
            else {
                $(".buttons button").attr('disabled', true);
            }
        },
        
        addAccountTmpl: function() {
            var self = this;
            var html = $("#add_account_tmpl").html();
                html = html.replace(/{x}/g, $(".account_panel").length);

            var $obj = $(html);
            $("#accounts_list").append($obj);

            $obj.fadeIn();

            $obj.find('.account_name').autocomplete({
                source: $("#account_lookup_url").val(),
                minLength: 2,
                select: function( event, ui ) {
                    if ( ui.item ) {
                        var hidden = $(this).siblings('.member_id');
                        hidden.val(ui.item.member_id);

                        $(this).data("tag-id", ui.item.value.id );
                        $(this).attr("disabled", true).addClass('tagging');
                        $(this).parent().find(".tag_remove").show();
                        $(this).parents('.account_panel').find('.profile-thumb').attr('src', ui.item.thumb_url);

                        event.preventDefault();
                    }
                },
                focus: function(event, ui) {
                    //$(this).val( ui.item.value.name );
                    //event.preventDefault();
                },
                change: function(event, ui) {
                    if( ui.item ) {
                        //$(this).val( ui.item.value.name );
                        event.preventDefault();
                    }
                }
            }).blur(function(){
                    var input = $(this);
                    var def_val = input.attr('data-value');
                    if(!input.hasClass('tagging') && input.hasClass('tagged') ){
                        input.attr("disabled", true).val(def_val);
                        input.parent().find(".tag_remove").show();
                    }
            });

            $obj.find(".tag_remove").click(function() {
                if($(this).find("i").hasClass('fa-times')){
                    $(this).hide();
                    var input = $(this).parent().find(".account_name");
                    input.removeAttr("disabled").removeData("tag-id").removeClass("tagging").val("").focus();

                    var pt = input.parents('.account_panel').find('.profile-thumb');
                    pt.attr('src', pt.data('default-url'));
                }
            });

            // force select the first organisation role and trigger the changed event
            // so we capture the organisation_role_id data
            $obj.find('.select').select('selectByIndex', 0).trigger('changed');

            self.enableButtons(true);
        },
        
        save: function() {
            var self = this;
            
            var url = $("#accounts_list_form").attr('action');
            var params = $("#accounts_list_form").serialize();
            
            self.enableButtons(false);
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function (res) {
                    if( res.status == 'success' ) {
                        window.history.go(0);
                    }
                    
                    else if( res.status == 'failed' ) {
                        alertify.error( res.message );
                    }
                },
                error: function (xhr) {
                    alert("Failed to save account changes.");
                    self.enableButtons(true);
                }
            });
        },
        
        remove: function(account_id, callback) {
            
            confirm("Are you sure you want to remove this user account?", function() {
                var url = $("#account_removal_url").val();
                var params = {
                    account_id: account_id
                };
                $.ajax({
                    url: url,
                    data: params,
                    type: 'post',
                    dataType: 'json',
                    success: function( res ) {
                        if( res.status == 'success' ) {
                            if( callback && $.isFunction(callback) ) {
                                callback();
                            }

                            alertify.success('Account removed from this organisation successfully.');
                        }

                        else if( res['message'] ) {
                            alertify.error( res.message );
                        }
                    },
                    error: function( xhr ) {
                        alertify.error('Account removal failed unexpectedly. Please try again');
                    }
                });
            });
        }
    },
    
    roles: {
        
        init: function() {
            this.bindUI();
        },

        loadRoleData: function(role_id) {
            var self = this;
            var url = $("#role_data_url").val();
            var params = {
                role_id: role_id
            };
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function( response ) {
                    if( response.status == 'failed' ) {
                        alert( response.message );
                    }
                    
                    else {
                        self.fillForm( response.role );
                    }
                },
                error: function( xhr ) {
                    console.log(xhr.responseText);
                }
            });
        },

        enableForm: function(enable) {
            if( enable ) {
                $("#role_form_area input, #role_form_area button").removeAttr('disabled');
            }
            
            else {
                $("#role_form_area input, #role_form_area button").attr('disabled', true);
            }
        },
        
        fillForm: function(data) {
            // reset
            this.enableForm(false);
            $("#role_data_form input:checkbox").removeAttr('checked');
            
            // begin fill
            this.setRoleId(data.OrganisationRole.id);
            $("#role_data_form #role_name").val(data.OrganisationRole.name);
            $("#role_data_form #admin_access").val(data.OrganisationRole.admin_access);
            
            if( data.OrganisationRole.admin_access ) {
                $("#role_data_form #admin_access").attr('checked', true);
            }
            else {
                $("#role_data_form #admin_access").removeAttr('checked');
            }
            
            for(var i = 0; i < data.OrganisationRoleModule.length; i++) {
                var role_module = data.OrganisationRoleModule[i];
                
                $("#role_data_form .module_checkbox").each(function() {
                    if( $(this).val() == role_module.module_id ) {
                        
                        $(this).siblings('.role_id').val( role_module.organisation_role_id );
                        $(this).siblings('.id').val( role_module.id );
                        
                        // we are currently doing the check client side to determine if or not
                        // to check the boxes. We have no solution from the api to return disabled
                        // record ids
                        if( role_module.active == 1 ) {
                            $(this).attr('checked', true);
                            var menu_ids = role_module.module_menu_ids;
                            
                            if( menu_ids ) {
                                var ids = menu_ids.split(",");

                                $(this).parents('li').find('.menu_checkbox').each(function() {
                                    for(var x = 0; x < ids.length; x++) {
                                        var id = ids[x];

                                        if( $(this).val() == id ) {
                                            $(this).attr('checked', true);
                                        } 
                                    }
                                });
                            }
                        }
                    } 
                    
                    
                });
            }
            
            // enable edit btn
            $("#role_form_area .actions button").removeAttr('disabled');
        },
        
        emptyForm: function() {
            $("#role_form_area .actions button").attr('disabled', true);
            $("#role_data_form input:checkbox").removeAttr('checked');
            $("#role_data_form input:text, #role_data_form input:hidden").val('');
            $("#role_data_form button").removeAttr('disabled');
            
            $("#role_data_form input:text:first").focus();
        },
        
        addPlaceholderItem: function() {
            if( $("a.list-placeholder").length > 0 ) {
                return;
            }
            
            var li = $("<a />").attr({
                'href': '#',
                'data-id': ''
            }).addClass('list-group-item list-placeholder')
                    .html("<i class='fa fa-chevron-right'></i> <span>[Role Name Here]</span>");
            
            $('#roles_list.list-group').append(li);
        },
        
        removePlaceholderItem: function() {
            $("a.list-placeholder").remove();
        },
        
        updatePlaceholderItem: function(id) {
            $("a.list-placeholder").data('id', id).removeClass('list-placeholder');
        },
        
        bindUI: function() {
            var self = this;
            
            $("#add_role").click(function() {
                self.enableForm(true);
                self.emptyForm();
                self.addPlaceholderItem();
            });
            
            $("#role_edit_btn").click(function() {
                self.enableForm(true);
            });
            
            $("#role_del_btn").click(function() {
                self.deleteRole( $(".list-group-item.selected").data('id') );
            });
            
            $("#role_data_form #cancel_btn").click(function() {
                self.enableForm(false);
                self.removePlaceholderItem();
            });
            
            // role list items
            $("#roles_list").on('click', '.list-group-item', function(e) {
                e.preventDefault();
                $(".list-group-item").removeClass('selected');
                
                self.loadRoleData( $(this).data('id') );
                $(this).addClass('selected');
            });
            
            // role list item checkboxes
            $("#roles_list .list-group-item input:checkbox").change(function(e) {
                e.stopPropagation();
            });
            
            $("#role_data_form .module_checkbox").change(function() {
                if( $(this).is(":checked") ) {
                    $(this).parents('li').find('.menu_checkbox').attr('checked', true).removeAttr('disabled');
                }
                else {
                    $(this).parents('li').find('.menu_checkbox').removeAttr('checked').attr('disabled', true);
                }
            });
            
            $("#role_data_form .menu_checkbox").change(function() {
                if( $(this).is(":checked") ) {
                    $(this).parents(".module_li").find('.module_checkbox').attr('checked', true);
                }
            });
            
            // role form role name input
            $("#role_data_form #role_name").keyup(function() {
                if( $(this).val() ) {
                    $("a.list-placeholder span").html( $(this).val() );
                } else {
                    $("a.list-placeholder span").html( "[Role Name Here]" );
                }
            });
            
            // role form admin access field
            $("#role_data_form #admin_access").change(function() {
                $(this).val( $(this).is(':checked') ? 1 : 0 );
            });
            
            // bind form submit
            $("#role_data_form").submit(function(e) {
                e.preventDefault();
                
                self.save();
            });
        },
        
        save: function() {
            var self = this;
            var url = $("#role_data_form").attr('action');
            var params = $("#role_data_form").serialize();
            
            self.enableForm(false);
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function( response ) {
                    if( response.status == 'success' ) {
                        alertify.success( response.message );
                        // set role id
                        self.setRoleId( response.role_id );
                        // enable edit btn
                        $("#role_form_area .actions button").removeAttr('disabled');
                        // reload role data so IDs are set in case user attempts to edit immediately
                        self.loadRoleData( response.role_id );
                    }
                    
                    else {
                        alert(response.message);
                        self.enableForm(true);
                    }
                },
                error: function( xhr ) {
                    alert("Failed to save role changes. Please try again");
                }
            });
        },
        
        setRoleId: function(role_id) {
            this.updatePlaceholderItem( role_id );
            $(".role_id").val( role_id );
        },
        
        deleteRole: function(role_id) {
            var self = this;
            
            confirm('Are you sure you want to delete this role and related permissions?', function() {
                var url = $("#role_data_form").attr('action');
                var params = {
                    action: 'delete',
                    role_id: role_id
                };

                self.enableForm(false);
                
                $.ajax({
                    url: url,
                    data: params,
                    type: 'post',
                    dataType: 'json',
                    success: function( response ) {
                        if( response.status == 'success' ) {
                            alertify.success("Role definition deleted successfully");
                            $(".list-group-item.selected").hide('fast');
                            
                            self.emptyForm();
                        }
                        
                        else {
                            alertify.error( response.message );
                        }
                    },
                    error: function( xhr ) {
                        alertify.error( "Failed to complete delete operation. Please try again." );
                    }
                });
            });
        } 
    }
    
    /*table: {
        
        setup: function(accounts) {
            
            $("#accounts-table tbody tr td.info").click(function() {
                $("#accounts-table tbody tr").removeClass("selected");
                
                $(this).parents('tr').addClass("selected");
                
                var account_id = $(this).data('id');
                accounts.profile.load(account_id);
            });
            
            $("#accounts-table tbody tr:first td.info").click();
            
            $("#add_btn").click(function(e) {
                e.preventDefault();
                accounts.editor.load();
            });
            
            $("#del_btn").click(function(e) {
                e.preventDefault();
                
                accounts.table.delete();
            });
        },
        
        selected: function() {
            var ids = [];
            
            $("#accounts-table tbody tr td input:checked").each(function() {
                ids.push( $(this).val() );
            });
            
            return ids;
        },
        
        delete: function() {
            var selected = this.selected();
            
            if( selected && selected.length == 0 ) {
                alert("Please select accounts to delete in order to continue");
                return;
            }
            
            if( !confirm("Are you sure you would like to remove these accounts?") ) {
                return;
            }
            
            var url = $("#accounts-table #del_btn").attr("href");
            var params = {account_id: selected};
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function() {
                    $("#accounts-table tbody tr td input:checked").each(function() {
                        $(this).parents("tr").remove();
                    });
                },
                error: function(xhr) {
                    alert("Failed to remove selected accounts. Please try again later");
                }
            });
        }
    },
    
    profile: {
        
        setup: function(accounts) {
            $("#account_view #edit_btn").click(function() {
                var account_id = $("#accounts-table tbody tr.selected td.info").data('id');
                accounts.editor.load(account_id);
            });
        },
        
        load: function(account_id) {
            
            var url = $("#account_profile_url").val();
            var params = {account_id: account_id};
            
            $("#acccount_view .panel-body").html("<div class='wrapper-lg'><h4>Loading Profile. Please wait ...</h4></div>");
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                success: function(res) {
                    $("#account_view .panel-body").html(res);
                },
                error: function(xhr) {
                    $("#acccount_view .panel-body").html("<div class='wrapper-lg'><h3>An Error Occured Whiles Loading Profile To View</h3><div class='muted'>" + xhr.responseText + "</div></div>");
                }
            });
        }
    },
    
    editor: {
        
        load: function(account_id) {
            var self = this;
            
            var url = $("#accounts-table #add_btn").attr('href');
            var params = {};
            
            if( account_id ) {
                params['account_id'] = account_id;
            }
            
            $("#acccount_view .panel-body").html("<div class='wrapper-lg'><h4>Loading Profile. Please wait ...</h4></div>");
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                success: function(res) {
                    $("#account_view .panel-body").html(res);
                    self.configure();
                },
                error: function(xhr) {
                    $("#acccount_view .panel-body").html("<div class='wrapper-lg'><h3>An Error Occured Whiles Loading Profile To View</h3><div class='muted'>" + xhr.responseText + "</div></div>");
                }
            });
        },
        
        configure: function() {
            var self = this;
            
            $("#account_view #cancel-btn").click(function(e) {
                e.preventDefault();
                $("#accounts-table tbody tr.selected td.info").click(); 
            });
            
            $("#account_view form").submit(function(e) {
                e.preventDefault();
                
                self.save();
            });
                    
            $("#account_view #username").blur(function() {
                if( !$(this).hasClass("valid") && !$(this).hasClass("invalid") && this.checkValidity()  ) {
                    self.checkUsername( $(this).val() );
                }
                
            }).keyup(function() {
                $(this).removeClass("valid invalid");
            });
        },
        
        checkUsername: function(username) {
            var url = $("#check_username_url").val();
            var params = {
                'username': username
            };
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function(response) {
                    if( response.status == 'available' ) {
                        $("#account_view .availability").removeClass("fa-ban text-danger").addClass("availability fa fa-check text-success").parents(".form-group").removeClass("text-danger");
                        $("#account_view #username").addClass("valid");
                        
                        if( response.profile.Member ) {
                            $("#account_view #first_name").val( response.profile.Member.first_name );
                            $("#account_view #last_name").val( response.profile.Member.last_name );
                            $("#account_view #gender").val( response.profile.Member.gender );
                            $("#account_view #dob").val( response.profile.Member.dob );
                        }
                    }
                    
                    else {
                        $("#account_view .availability").removeClass("fa-check text-success").addClass("availability fa fa-ban text-danger").parents(".form-group").addClass("text-danger");;
                        $("#account_view .pf").val("");
                        $("#account_view #username").addClass("invalid");
                    }
                },
                error: function(xhr) {
                    alert("Username verification failed");
                    console.log(xhr.responseText);
                }
            });
        },
        
        save: function() {
            
            if( $("#account_view .invalid").length > 0 ) {
                alert("This form has an error. Please check supplied inputs for validity");
                return;
            }
            
            var url = $("#account_view form").attr('action');
            var params = $("#account_view form").serialize();
            
            $.ajax({
                url: url,
                data: params,
                type: 'post',
                dataType: 'json',
                success: function(res) {
                    if( res['status'] == 'success' ) {
                        window.history.go(0);
                    }
                    
                    else {
                        alert(res['message']);
                    }
                },
                error: function() {
                    alert("Failed to save changes to account information");
                }
            });
        }
    }*/
});

$(function() {
    var accounts = new AccountsView(); 
});